package com.lsyw.intergrate.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsyw.intergrate.common.BaseResult;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.entity.Massif;
import com.lsyw.intergrate.entity.SysUser;
import com.lsyw.intergrate.entity.SysUsersRoles;
import com.lsyw.intergrate.entity.UnopDept;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.lsyw.intergrate.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-04-21
 */
@Api(tags = "用户表")
@RestController
@RequestMapping("/sys-user")
public class SysUserController {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUsersRolesService sysUsersRolesService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private UnopDeptService unopDeptService;
    @Autowired
    private MassifService massifService;

    /**
     * 通过id查询
     */
    @GetMapping("/get-by-id")
    public Result getById(String id) {
        return Result.successResult(sysUserService.getById(id));
    }

    /**
     * 配置角色
     */
    @GetMapping("/set/roles")
    @ApiOperation(value = "配置角色", notes = "配置角色", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "roIds", value = "角色id ,拼接字符串", required = true, paramType = "query", dataType = "String")
    })
    public Result setRoles(String roIds, String userId) {
        if (!StringUtils.isEmpty(roIds)) {
            List<String> rolesIds = sysUsersRolesService.list(new QueryWrapper<SysUsersRoles>().eq("user_id", userId)).stream().map(SysUsersRoles::getId).collect(Collectors.toList());
            rolesIds.stream().forEach(roleId -> {
                this.sysUsersRolesService.removeById(roleId);
            });
            Result.successResult(null);
        }
        List<String> rolesIds = sysUsersRolesService.list(new QueryWrapper<SysUsersRoles>().eq("user_id", userId)).stream().map(SysUsersRoles::getId).collect(Collectors.toList());
        rolesIds.stream().forEach(roleId -> {
            this.sysUsersRolesService.removeById(roleId);
        });

        String[] roleIds = roIds.split(",");
        for (String id : roleIds) {
            SysUsersRoles sysUsersRoles = new SysUsersRoles();
            sysUsersRoles.setUserId(userId);
            sysUsersRoles.setRoleId(id);
            sysUsersRoles.setRoleIds(null);
            sysUsersRoles.setId(IdUtil.simpleUUID());
            //sysUsersRoles.setGmtCreateUser();
            sysUsersRoles.setGmtCreate(new Date());
            // sysUsersRoles.setGmtModifiedUser();
            sysUsersRoles.setGmtModified(new Date());
            // sysUsersRoles.setStatus();
            sysUsersRoles.setDelFlag(0);
            //   sysUsersRoles.setGmtCreateUserName();
            this.sysUsersRolesService.save(sysUsersRoles);
        }
        return Result.successResult(null);
    }


    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增", notes = "新增", httpMethod = "POST")
    public Result save(@RequestBody SysUser sysUser) {
        sysUser.setId(IdUtil.simpleUUID());
        String salt = IdUtil.simpleUUID();
        sysUser.setSalt(salt);
        sysUser.setStatus(0);
        sysUser.setCreatedTime(new Date());
        String password="lxhb@2024";
        sysUser.setPassword(SecureUtil.md5(password + salt));
        sysUserService.save(sysUser);
        return Result.successResult(null);
    }


    /**
     * 删除
     */
    @GetMapping("/del-by-id")
    @ApiOperation(value = "删除", notes = "删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result delById(String id) {
        SysUser user = sysUserService.getById(id);
        user.setDelFlag(1);
        user.setIsDelete(1);
        this.sysUserService.updateById(user);
        return Result.successResult(null);
    }


    /**
     * 禁用/启用
     */
    @GetMapping("/delete-status")
    @ApiOperation(value = "禁用/启用", notes = "禁用/启用", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "1启用   2注销", required = true, paramType = "query", dataType = "Integer")
    })
    public Result delete(String id, Integer status) {
        SysUser sysUser = this.sysUserService.getById(id);
        sysUser.setStatus(status);
        this.sysUserService.updateById(sysUser);
        return Result.successResult(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result updateById(@RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return Result.successResult(null);
    }


    /**
     * 查询列表
     */
    @PostMapping("/list")
    public Result list(@RequestBody SysUserReqVo sysUser) {
        final LambdaQueryWrapper<SysUser> lambda = new QueryWrapper<SysUser>().lambda();
        this.buildCondition(lambda, sysUser);
        return Result.successResult(sysUserService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
    public BaseResult<IPage<SysUser>> page(@RequestBody PageInfo pageInfo) {
        Map<String, Object> condition = pageInfo.getCondition();
        Page<SysUser> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        final LambdaQueryWrapper<SysUser> lambda = new QueryWrapper<SysUser>().lambda();
        lambda.eq(SysUser::getIsDelete, 0);
        if (condition.get("deptId") != null && !StringUtils.isEmpty(condition.get("deptId").toString())) {
            lambda.eq(SysUser::getDeptId, condition.get("deptId"));
        }
        if (condition.get("name") != null && !StringUtils.isEmpty(condition.get("name").toString())) {
            lambda.like(SysUser::getName, condition.get("name"));
        }
        //   lambda.eq(SysUser:: getDeptId,0);
        IPage<SysUser> userPage = this.sysUserService.page(page, lambda);
        List<SysUser> record = userPage.getRecords();
        record.stream().forEach(sysUser -> {
            List<String> roleNames = new ArrayList<>();
            List<String> rolesIds = sysUsersRolesService.list(new QueryWrapper<SysUsersRoles>().eq("user_id", sysUser.getId()).ne("role_id","")).stream().map(SysUsersRoles::getRoleId).collect(Collectors.toList());
            rolesIds.stream().forEach(roleId -> {
                roleNames.add(sysRoleService.getById(roleId).getName());
            });
            sysUser.setRoleNames(roleNames);

            String deptId = sysUser.getDeptId();
            UnopDept dept = this.unopDeptService.getById(deptId);
            Massif massif = this.massifService.getById(sysUser.getProjectId());
            if (ObjectUtil.isNotNull(massif)){
                sysUser.setProjectName(massif.getName());
            }
            if (ObjectUtil.isNotNull(dept)){
                sysUser.setDept(dept);
                sysUser.setDeptName(dept.getName());
            }
        });
        return BaseResult.successResult(userPage);
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<SysUser> lambda, SysUserReqVo param) {
        if (!StringUtils.isEmpty(param.getId())) {
            lambda.eq(SysUser::getId, param.getId());
        }
        if (!StringUtils.isEmpty(param.getName())) {
            lambda.eq(SysUser::getName, param.getName());
        }
        if (!StringUtils.isEmpty(param.getPassword())) {
            lambda.eq(SysUser::getPassword, param.getPassword());
        }
        if (!StringUtils.isEmpty(param.getSalt())) {
            lambda.eq(SysUser::getSalt, param.getSalt());
        }
        if (!StringUtils.isEmpty(param.getPhone())) {
            lambda.eq(SysUser::getPhone, param.getPhone());
        }
        if (!StringUtils.isEmpty(param.getJyzt())) {
            lambda.eq(SysUser::getJyzt, param.getJyzt());
        }
        if (!StringUtils.isEmpty(param.getSsdwbm())) {
            lambda.eq(SysUser::getSsdwbm, param.getSsdwbm());
        }
        if (!StringUtils.isEmpty(param.getSjdh())) {
            lambda.eq(SysUser::getSjdh, param.getSjdh());
        }
        if (!StringUtils.isEmpty(param.getXb())) {
            lambda.eq(SysUser::getXb, param.getXb());
        }
        if (!StringUtils.isEmpty(param.getIdCard())) {
            lambda.eq(SysUser::getIdCard, param.getIdCard());
        }
        if (!StringUtils.isEmpty(param.getDeptId())) {
            lambda.eq(SysUser::getDeptId, param.getDeptId());
        }
        if (!StringUtils.isEmpty(param.getType())) {
            lambda.eq(SysUser::getType, param.getType());
        }
        if (!StringUtils.isEmpty(param.getSort())) {
            lambda.eq(SysUser::getSort, param.getSort());
        }
        if (!StringUtils.isEmpty(param.getPhoto())) {
            lambda.eq(SysUser::getPhoto, param.getPhoto());
        }
        if (!StringUtils.isEmpty(param.getClientType())) {
            lambda.eq(SysUser::getClientType, param.getClientType());
        }
        if (!StringUtils.isEmpty(param.getStatus())) {
            lambda.eq(SysUser::getStatus, param.getStatus());
        }
        if (!StringUtils.isEmpty(param.getCreatorId())) {
            lambda.eq(SysUser::getCreatorId, param.getCreatorId());
        }
        if (!CollectionUtils.isEmpty(param.getCreatedTimeList())) {
            lambda.ge(SysUser::getCreatedTime, param.getCreatedTimeList().get(0));
            lambda.le(SysUser::getCreatedTime, param.getCreatedTimeList().get(1));
        }
        if (!CollectionUtils.isEmpty(param.getUpdatedTimeList())) {
            lambda.ge(SysUser::getUpdatedTime, param.getUpdatedTimeList().get(0));
            lambda.le(SysUser::getUpdatedTime, param.getUpdatedTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdatedUser())) {
            lambda.eq(SysUser::getUpdatedUser, param.getUpdatedUser());
        }
        if (!StringUtils.isEmpty(param.getIsDelete())) {
            lambda.eq(SysUser::getIsDelete, param.getIsDelete());
        }
        lambda.orderBy(true, false, SysUser::getId);
    }


    /**
     * 请求model
     */
    @Data
    @AllArgsConstructor
    private static class SysUserReqVo extends SysUser {
        private List<String> createdTimeList; // 创建时间起止
        private List<String> updatedTimeList; // 更新时间起止
    }


}
